﻿using System.Linq.Expressions;
using Jst.Application.Contracts.Contracts;
using Jst.IRepository.Repositories;
using Jst.Repository.SqlSugar.Internal;
using SqlSugar;

namespace Jst.Repository.SqlSugar.Repositories
{
    public abstract class SugarRepositoryBase<T> : IRepository<T>
        where T : class, new()   // ← 只保留 class / new()
    {

        private readonly IDbContext _dbContext;

        protected SugarRepositoryBase(IDbContext dbContext)
        {
            Guard.EnsureAggregateRoot<T>();   // 运行时检查特性
            _dbContext = dbContext;
        }

        protected ISqlSugarClient Db => _dbContext.DefaultDb;

        public virtual async Task<T?> GetAsync(object id, CancellationToken ct = default)
            => await Db.Queryable<T>().InSingleAsync(id);

        public virtual async Task InsertAsync(T entity, CancellationToken ct = default)
            => await Db.Insertable(entity).ExecuteCommandAsync(ct);

        public virtual async Task UpdateAsync(T entity, CancellationToken ct = default)
            => await Db.Updateable(entity).ExecuteCommandAsync(ct);

        public virtual async Task DeleteAsync(T entity, CancellationToken ct = default)
            => await Db.Deleteable(entity).ExecuteCommandAsync(ct);

        public virtual async Task<bool> ExistsAsync(Expression<Func<T, bool>> predicate, CancellationToken ct = default)
            => await Db.Queryable<T>().AnyAsync(predicate, ct);

        public virtual async Task<int> CountAsync(Expression<Func<T, bool>>? predicate = null, CancellationToken ct = default)
            => await Db.Queryable<T>().WhereIF(predicate != null, predicate).CountAsync(ct);


    }
}